package com.nowcoder.community.service;

import com.nowcoder.community.mapper.CommentMapper;
import com.nowcoder.community.mapper.DiscussPostMapper;
import com.nowcoder.community.pojo.Comment;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service("commentService")
public class CommentServiceImpl implements CommentService, CommunityConstant{

    @Autowired
    @Qualifier("commentMapper")
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    @Qualifier("discussPostMapper")
    private DiscussPostMapper discussPostMapper;

    @Override
    public List<Comment> findCommentByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentByEntity(entityType, entityId, offset, limit);
    }

    @Override
    public int findCountByEntity(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    /**
     * 方法中有添加评论和更新评论数量两个操作，这两个操作是同步的，
     * 要么同时成功，要么同时失败，所以要添加事务
     * @param comment 评论实例
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @Override
    public int addComment(Comment comment) {

        if (comment == null){
            throw new IllegalArgumentException("参数不能为空！");
        }


        //转义html标签，html标签不能显示在页面中
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        //顾虑评论中的敏感词
        comment.setContent(sensitiveFilter.filterSensitiveWords(comment.getContent()));
        //添加评论，rows为添加的评论数量
        int rows = commentMapper.addComment(comment);

        //更新帖子中评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST){

            int count = commentMapper.selectCountByEntity(comment.getEntityType(),
                    comment.getEntityId());

            discussPostMapper.updateCommentCount(comment.getEntityId(), count);
        }

        return rows;
    }

    @Override
    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }

    @Override
    public int removeCommentsByUserId(int userId) {
        return commentMapper.deleteCommentsByUserId(userId);
    }


}
